package com.yaxin.system.service.impl;

import com.yaxin.common.core.utils.StringUtils;
import com.yaxin.outsourcing.domain.LoginResult;
import com.yaxin.system.service.IWorkProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import static com.yaxin.outsourcing.utils.OaLoginUtil.login;


@Slf4j
@Service
public class WorkProcessService implements IWorkProcessService {

    @Autowired
    private RestTemplate restTemplate;


    LoginResult result = null;


    String applicationServer = "10.118.50.12";
    Integer applicationPort = 56333;
    String userName = "202311080002";
    String ssoClient = "HR"; //?????
    String key = "hrsystem";

    /**
   {
        try {
            result = login(applicationServer, applicationPort, userName, ssoClient, key);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        if( StringUtils.equals( "success", result.getType() )) {
            System.out.println("xtoken=" + result.getToken() );
        }else {
            System.out.println("message:" + result.getMessage() );
        }
    }
     **/

//    private final String baseUrl = "http://10.118.50.12:56333/x_desktop/sso.html?client=HR&xtoken={xtoken}&redirect={baseUrl_2}";
    private final String baseUrl_2 = "http://10.118.50.12:56333/x_processplatform_assemble_surface/jaxrs/work/process";

    public ResponseEntity<String> createWorkProcess(String processFlag, String  requestBody) {
        // 构建完整的认证URL
        String redirectUrl = baseUrl_2 + "/" + processFlag;
//        String redirectUrl = baseUrl_2;
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.set("Cookie", "x-token="+result.getToken());
        headers.set("data", requestBody);
        // 创建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        return restTemplate.exchange(redirectUrl, HttpMethod.POST, requestEntity, String.class);
    }

    public ResponseEntity<String> taskProcessing(String id) {
        String url = "http://10.118.50.12:56333/x_processplatform_assemble_surface/jaxrs/task/{id}/processing";
        String redictUrl = url.replace("{id}", id);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.set("Cookie", "x-token="+result.getToken());
        String requestBody = "{}";
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        return restTemplate.exchange(redictUrl, HttpMethod.POST, requestEntity, String.class);
    }
}
